import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { Modal, Radio, Form, Input, Checkbox, Switch, Space, Button, message, Upload, Spin } from 'antd';
import { MultilingualInput, SelectFileOrFolder } from '@inbiz/setters';
import { useInbiz } from '../../../store/hooks/useInbiz';
import './styles.less';
import style1Img from '../assets/style1.svg';
import style2Img from '../assets/style2.svg';
import DocConfig from '@inbiz/basic/DocConfig'; // 文件夹目录选择组件
import { TextWidget, getMessage } from '@inbiz/react';
import { InfoCircleOutlined } from '@ant-design/icons';
import { getPlatform } from '@inbiz/utils';
import UploadTemplate from './UploadTemplate';

type SelectFolderProps = Parameters<typeof SelectFileOrFolder>[0];
export interface IDmsSettingProps {
  value?: string;
  visible: boolean;
  currentData: any;
  onOk: (value: string) => void;
  onCancel: () => void;
  onChange?: (value: string) => void;
}

export const DmsSetting: React.FC<IDmsSettingProps> = (props) => {
  const { currentData, onCancel, onOk, visible } = props;
  const [isModalVisible, $isModalVisible] = useState(false); // DMS设置弹窗开关
  const [isOpenAdvancedSearch, $isOpenAdvancedSearch] = useState(currentData?.advancedSearch); // 是否开启高级搜索
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const criteriaConfigOptions = useMemo(
    () => [
      { label: 'SearchEngine.content', value: 1 },
      { label: 'SearchEngine.fileName', value: 2 },
      { label: 'SearchEngine.folderName', value: 4 },
      { label: 'SearchEngine.label', value: 3 },
    ],
    [],
  );
  useEffect(() => {
    $isModalVisible(visible);
    // 显示时如果是修改，通过currentData回填表单
  }, [visible]);

  // DMS设置弹窗确定按钮触发事件
  const handleOk = useCallback(() => {
    form.validateFields().then((values) => {
      values.isDelete = false;
      values.isEdit = true;
      values.isShow = true;
      values.isFile = currentData.isFile;
      values.isFolder = currentData.isFolder;
      // 赋值
      onOk && onOk({ ...currentData, ...values });
      // 重置表单
      form.resetFields();
    });
  }, [onOk]);

  // DMS设置弹窗取消事件
  const handleCancel = () => {
    // 重置表单
    form.resetFields()
    $isOpenAdvancedSearch(false);
    onCancel && onCancel();
  };

  // 点击开启高级搜索开关触发事件
  const onOpenAdvancedSearch = (checked: boolean) => {
    $isOpenAdvancedSearch(checked);
  };

  const inbiz = useInbiz();
  const docConfigprops = {
    mode: 'SelectFolder',
    lang: 'zh-CN',
    inbiz,
    showTeam: true,
    showPersonalLibrary: true,
    hidePersonalChildren: true,
    placeholder: getMessage('SearchEngine.tips.clickSelectFolder'),
  } as unknown as SelectFolderProps;

  
  
  return (
    <div>
      <Modal
        title={getMessage('SearchEngine.dmsEditSearchRange')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText={getMessage('SearchEngine.cancel')}
        okText={getMessage('SearchEngine.determine')}
        width={800}
      >
        <Spin spinning={loading}>
          <Form
            form={form}
            name="dmsSetting"
            initialValues={currentData}
            autoComplete="off"
            className="search-dms-setting-wrapper"
          // size='small'
          >
            <Form.Item
              label={getMessage('SearchEngine.labelName')}
              name="title"
              rules={[
                { required: true, message: getMessage('SearchEngine.tips.pleaseEnterTheLabelName') },
              ]}
            >
              <MultilingualInput value={currentData.title} />
            </Form.Item>

            <Form.Item label={getMessage('SearchEngine.tagNumber')} name="guid">
              <Input value={currentData.guid} disabled />
            </Form.Item>

            {(currentData.isDMS) && <>
              <Form.Item
                required
                label={`DMS${getMessage('SearchEngine.searchCriteriaConfiguration')}`}
                style={{ marginBottom: 0 }}
              >
                <Form.Item
                  getValueFromEvent={(e) => {
                    return e
                      ? e.map((item: number) => criteriaConfigOptions.find((i) => i.value === item))
                      : [];
                  }}
                  getValueProps={(e) => {
                    return e ? { value: e.map((item: { value: number }) => item.value) } : e;
                  }}
                  name="searchType"
                  rules={[
                    {
                      required: true,
                      message: getMessage('SearchEngine.tips.searchCriteriaConfigurationTips'),
                    },
                  ]}
                >
                  <Checkbox.Group>
                    {criteriaConfigOptions.map((item: any) => (
                      <Checkbox value={item.value}>{getMessage(item.label)}</Checkbox>
                    ))}
                  </Checkbox.Group>
                </Form.Item>
                <Form.Item
                  name="customRange"
                  getValueFromEvent={(e) => {
                    return !e.includes('allFolder') ? ['allFolder', ...e] : e;
                  }}
                >
                  <Checkbox.Group>
                    <Checkbox value="allFolder" key="allFolder">
                      <TextWidget>SearchEngine.fullLibrary</TextWidget>
                    </Checkbox>
                    <Checkbox value="curfolder" key="curfolder">
                      <TextWidget>SearchEngine.currentFolder</TextWidget>
                    </Checkbox>
                  </Checkbox.Group>
                </Form.Item>
              </Form.Item>

              <Form.Item
                label={`DMS${getMessage('SearchEngine.searchFolders')}`}
                name="selectFolderID"
                className="selectFolder"
              >
                <SelectFileOrFolder {...docConfigprops} />
              </Form.Item>
            </>}
            {
              currentData.viewType != 'smallPanelView' && <Form.Item name="searchMode" label={getMessage('SearchEngine.searchBy')}>
                <Switch defaultChecked={currentData?.searchMode} />
              </Form.Item>
            }

            {getPlatform() === 'web' && currentData.isFile && (
              <>
                <Form.Item
                  name="imgSearchImg"
                  label={getMessage('SearchEngine.imgSearchImg')}
                  tooltip={{
                    title: getMessage('SearchEngine.imgSearchTips'),
                    icon: <InfoCircleOutlined />,
                  }}
                >
                  <Switch defaultChecked={currentData?.imgSearchImg} />
                </Form.Item>
                <Form.Item name="keywordAtlas" label={getMessage('SearchEngine.inform')}>
                  <Switch defaultChecked={currentData?.keywordAtlas} />
                </Form.Item>
              </>
            )}

            {getPlatform() === 'web' && (
              <Form.Item
                label={getMessage('SearchEngine.advancedSearch')}
                name="advancedSearch"
              >
                <Switch
                  onChange={onOpenAdvancedSearch}
                  defaultChecked={currentData?.advancedSearch}
                />
              </Form.Item>
            )}

            {isOpenAdvancedSearch && getPlatform() === 'web' && !currentData.isAll && currentData.viewType != 'smallPanelView' && (
              <Form.Item
                label={getMessage('SearchEngine.advancedSearchStyle')}
                name="advancedSearchStyle"
              >
                <Radio.Group className="advancedSearchStyle" >
                  <div className="advancedSearchStyle-item">
                    <Radio value="style1">
                      <img src={style1Img} />
                    </Radio>
                  </div>
                  <div className="advancedSearchStyle-item">
                    <Radio value="style2">
                      <img src={style2Img} />
                    </Radio>
                  </div>
                </Radio.Group>
              </Form.Item>
            )}

            {getPlatform() === 'web' && currentData.viewType == 'smallPanelView' && (
              <>
                <UploadTemplate
                  form={form}
                  currentData={currentData}
                  setLoading={setLoading}
                />
                <Form.Item
                  label={getMessage('SearchResultEngine.resultsSearchCriteria')}
                  name="resultsSearchCriteria"
                >
                  <Input />
                </Form.Item>
              </>
            )}

          </Form>
        </Spin>
      </Modal>
    </div>
  );
};
